######################################################################
# 这个脚本负责实现主场景的单位管理功能
######################################################################

extends Node2D

@onready var units = []    # 单位列表
@onready var selectedUnits = []

func _ready():
	units = get_tree().get_nodes_in_group("units")

func _input(event):
	if Input.is_action_just_pressed("MouseLeftClick"):
		#clear_selected_units()
		print("nothing")

func clear_selected_units():
	print("clear all selected units")
	for unit in selectedUnits:
		unit.set_selected(false)

# 获取框选单位
func get_unit_in_area(object):
	# 计算边界范围
	var start = object.start
	var end = object.end
	var area = []
	area.append(Vector2(min(start.x, end.x), min(start.y, end.y)))
	area.append(Vector2(max(start.x, end.x), max(start.y, end.y)))
	
	# 选框标注
	selectedUnits = get_units_in_area(area)
	for unit in units:
		unit.set_selected(false)
	for unit in selectedUnits:
		unit.set_selected(true)
	print(selectedUnits)

# 从判断是否被框选住，选中者加入列表
func get_units_in_area(area):
	print("get units in area")
	var unitsGroup = []
	for unit in units:
		if (unit.position.x > area[0].x) and (unit.position.x < area[1].x):
			if (unit.position.y > area[0].y) and (unit.position.y < area[1].y):
				unitsGroup.append(unit)
	return unitsGroup

# 接受框选信号
func _on_main_camera_area_selected(object):
	get_unit_in_area(object)

